#!/usr/bin/python
# -*- coding: utf-8 -*-
#/*
# *      Copyright (C) 2011 by Tolin
# *
# *  This Program is free software; you can redistribute it and/or modify
# *  it under the terms of the GNU General Public License as published by
# *  the Free Software Foundation; either version 2, or (at your option)
# *  any later version.
# *
# *  This Program is distributed in the hope that it will be useful,
# *  but WITHOUT ANY WARRANTY; without even the implied warranty of
# *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# *  GNU General Public License for more details.
# *
# *  You should have received a copy of the GNU General Public License
# *  along with this program; see the file COPYING.  If not, write to
# *  the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# *  http://www.gnu.org/copyleft/gpl.html
# */

import urllib2, re, httplib, xbmc, xbmcgui, xbmcplugin, cookielib, xbmcaddon, os, urllib, urllib2, socket

icon = xbmc.translatePath(os.path.join(os.getcwd().replace(';', ''), 'icon.png'))
siteUrl = 'go2load.com'
httpSiteUrl = 'http://' + siteUrl

h = int(sys.argv[1])


def construct_request(params):
	return '%s?%s' % (sys.argv[0], urllib.urlencode(params))

def showMessage(heading, message, times = 50000):
#	xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s, "%s")'%(heading, message, times, icon))
	xbmc.executebuiltin('XBMC.Notification("%s", "%s", %s")'%(heading, message, times))
	
def GET(url):
	try:
		print 'def GET(%s):'%url
		req = urllib2.Request(url)
		f = urllib2.urlopen(req)
		a = f.read()
		f.close()
		return a
	except:
		showMessage('Не могу открыть URL def GET', url)
		return None

	

def ROOT():

        name='Фильмы'
        li = xbmcgui.ListItem(name)
        url = sys.argv[0] + '?mode=video_sub'
	href = httpSiteUrl + '/filmy/'
	url += '&url=%s'%urllib.quote_plus(href)
        xbmcplugin.addDirectoryItem(h, url, li, True)
        
	name='Мультфильмы'
        li = xbmcgui.ListItem(name)
        url = sys.argv[0] + '?mode=video_sub1'
	href = httpSiteUrl + '/video/mult/'
	url += '&url=%s'%urllib.quote_plus(href)
        xbmcplugin.addDirectoryItem(h, url, li, True)
	
	name='Документальные'
        li = xbmcgui.ListItem(name)
        url = sys.argv[0] + '?mode=video_sub1'
	href = httpSiteUrl + '/documentary/'
	url += '&url=%s'%urllib.quote_plus(href)
        xbmcplugin.addDirectoryItem(h, url, li, True)
	
#	name='Українське кіно'
#        li = xbmcgui.ListItem(name)
#        url = sys.argv[0] + '?mode=video_sub1'
#	href = httpSiteUrl + '/ukr_kino/'
#	url += '&url=%s'%urllib.quote_plus(href)
#        xbmcplugin.addDirectoryItem(h, url, li, True)
	
	name='СССР'
        li = xbmcgui.ListItem(name)
        url = sys.argv[0] + '?mode=video_sub1'
	href = httpSiteUrl + '/filmy/cccp/'
	url += '&url=%s'%urllib.quote_plus(href)
        xbmcplugin.addDirectoryItem(h, url, li, True)
	
#	name='Comedy Club Украина'
#        li = xbmcgui.ListItem(name)
#        url = sys.argv[0] + '?mode=video_sub1'
#	href = httpSiteUrl + '/filmy/comedy_club_ukraine/'
#	url += '&url=%s'%urllib.quote_plus(href)
#        xbmcplugin.addDirectoryItem(h, url, li, True)
	
#	name='Наша Russia'
#        li = xbmcgui.ListItem(name)
#        url = sys.argv[0] + '?mode=video_sub1'
#	href = httpSiteUrl + '/category/nasharussia/'
#	url += '&url=%s'%urllib.quote_plus(href)
#        xbmcplugin.addDirectoryItem(h, url, li, True)
	
#        name='Аудио'
#        li = xbmcgui.ListItem(name)
#        url = sys.argv[0] + '?mode=sound_sub'
#        xbmcplugin.addDirectoryItem(h, url, li, True)
	xbmcplugin.endOfDirectory(h)


def video_sub(params):

#	wurl = httpSiteUrl + '/filmy/'
	http = GET(urllib.unquote_plus(params['url']))
#	showMessage('url', params['url'])
#	http = GET(params['url'])
#	http = GET(url)
	if http == None: return False
#	 
#	r1 = re.compile('<div class="newspaneopen">(.*?)<td width="240" align="center" valign="top">',re.S).findall(http)
#	r1 = re.compile('<center><noindex><noindex>(.*?)<div class="navigation" align="center" style="margin-bottom:10px; margin-top:10px;">',re.S).findall(http)
#	r2 = re.compile('<td valign="top" colspan="2"><div class="story_content"><div align="center"><a href="(.*?)"><img src="(.*?)" border="0" alt="(.*?)" width="270" />').findall(r1[0])

#	r1 = re.compile('<center><noindex><noindex>(.*?)<div class="navigation" align="center" style="margin-bottom:10px; margin-top:10px;">',re.S).findall(http)
	r1 = re.compile('<center><noindex><noindex>(.*?)<td width="240" align="center" valign="top">',re.S).findall(http)
#	r2 = re.compile('<td valign="top" colspan="2"><div class="story_content"><div align="center"><a href="(.*?)"><img src="(.*?)" alt="(.*?)" width="270" border="0" /></a><br /> <span style="font-weight: bold;">(.*?)</span></div>',re.S).findall(r1[0])
	r2 = re.compile('<td valign="top" colspan="2"><div class="story_content"><div align="center"><a href="(.*?)"><img src="(.*?)" alt="(.*?)" width="270" border="0" /></a><br />',re.S).findall(r1[0])


	
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	for href, img, name in r2:

		i = xbmcgui.ListItem(unicode(name, "cp1251"), iconImage=img, thumbnailImage=img)
		u  = sys.argv[0] + '?mode=PLAY1'
		u += '&url=%s'%urllib.quote_plus(href)
#		u += '&img=%s'%urllib.quote_plus(img)
		xbmcplugin.addDirectoryItem(h, u, i, True)
	try:
#		rp = re.compile('<center><div class="navigation" align="center" style="margin-bottom:10px; margin-top:10px;">(.*?)</a></div></center></div>', re.DOTALL).findall(r1[0])
#		rp2 = re.compile('<a href="(.*?)">(.*?)</a>').findall(rp[0])
		rp = re.compile('<center><div class="navigation" align="center" style="margin-bottom:10px; margin-top:10px;">(.*?)</a></div></center></div>', re.S).findall(r1[0])
		rp2 = re.compile('<a href="(.*?)">(.*?)</a>').findall(rp[0])
		for href, nr in rp2:
			u = sys.argv[0] + '?mode=video_sub'
			u += '&url=%s'%urllib.quote_plus(href)
#			rPN = '[B][COLOR yellow]%s[/COLOR][/B]' % rPN
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass
		
    	xbmcplugin.endOfDirectory(h)


def video_sub1(params):

#	wurl = httpSiteUrl + '/filmy/'
	http = GET(urllib.unquote_plus(params['url']))
#	showMessage('url', params['url'])
#	http = GET(params['url'])
#	http = GET(url)
	if http == None: return False
	r1 = re.compile('<div class="newspaneopen">(.*?)<td width="240" align="center" valign="top">',re.S).findall(http)
	r2 = re.compile('<td valign="top" colspan="2"><div class="story_content"><div align="center"><a href="(.*?)"><img src="(.*?)" border="0" alt="(.*?)" width="270" />').findall(r1[0])
	
	if len(r2) == 0:
		showMessage('ПОКАЗАТЬ НЕЧЕГО', 'Нет элементов id,name,link,numberOfMovies')
		return False
	for href, img, name in r2:
		
		i = xbmcgui.ListItem(unicode(name, "cp1251"), iconImage=img, thumbnailImage=img)
		u  = sys.argv[0] + '?mode=PLAY2'
		u += '&url=%s'%urllib.quote_plus(href)
		xbmcplugin.addDirectoryItem(h, u, i, True)
	try:
		rp = re.compile('<center><div class="navigation" align="center" style="margin-bottom:10px; margin-top:10px;">(.*?)</a></div></center></div>', re.DOTALL).findall(http)[0]
		rp2 = re.compile('<a href="(.*?)">(.*?)</a>').findall(rp)
		for href, nr in rp2:
			u = sys.argv[0] + '?mode=video_sub1'
			u += '&url=%s'%urllib.quote_plus(href)
#			rPN = '[B][COLOR yellow]%s[/COLOR][/B]' % rPN
			i = xbmcgui.ListItem('[ Страница %s ]'%nr)
			xbmcplugin.addDirectoryItem(h, u, i, True)
	except:
		pass
		
    	xbmcplugin.endOfDirectory(h)


	
def PLAY1(params):
	http = GET(urllib.unquote_plus(params['url']))

	if http == None: return False

	rows = re.compile('div align="left"><br /> <a href="(.*?)" shape="rect"> <img src=',re.S).findall(http)
#	showMessage('rows', rows[0])	
	xbmc.Player().play(rows[0])

def PLAY2(params):
	http = GET(urllib.unquote_plus(params['url']))

	if http == None: return False
#	showMessage('http', http)
	rows = re.compile('<a href="ftp://(.*?)"> <img src=',re.S).findall(http)
#	showMessage('rows', rows[0])	
	xbmc.Player().play('ftp://'+rows[0])




def get_params(paramstring):
	param=[]
	if len(paramstring)>=2:
		params=paramstring
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]
	return param

params=get_params(sys.argv[2])


mode = None

try:
	mode = urllib.unquote_plus(params['mode'])
except:
	ROOT()

if mode == 'ROOT': ROOT()
if mode == 'video_sub': video_sub(params)
if mode == 'PLAY1': PLAY1(params)
if mode == 'video_sub1': video_sub1(params)
if mode == 'PLAY2': PLAY2(params)
